﻿using Core.Framework;
using Core.Framework.Common;
using iTool.ClusterComponent;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Threading.Tasks;

namespace SocketService
{
    public class iToolServiceProvider
    {

        public async Task<iToolClusterHostServer> StartAsync()
        {
            iToolHostBuilder builder = default;

#if DEBUG
            builder = this.Debug_iToolHostBuilder();
#else

            builder = this.Release_iToolHostBuilder();
#endif

            return await builder.BuildAndStartAsync();
        }

        private iToolHostBuilder Debug_iToolHostBuilder()
        {
            var builder = new iToolHostBuilder();

            var clusterOptions = new AdoNetClusterOptions();

            // 数据库配置
            clusterOptions.AdoNetOptions = new AdoNetOptions
            {
                DataSource = "10.0.1.9",
                UID = "Gas_News",
                PWD = "QGsga*!H0B1QXfPTo%tfNcc3e"
            };

            // 服务配置
            clusterOptions.EndpointsOptions = new EndpointsOptions();

            // 集群配置
            clusterOptions.ClusterOptions = new ClusterIdentificationOptions();

            // 响应超时时间配置
            clusterOptions.ResponseTimeout = TimeSpan.FromSeconds(30);

            builder.ConfigureServices(this.INIIServices);


            builder.UseAdoNetClustering(clusterOptions);

            return builder;
        }

        private iToolHostBuilder Release_iToolHostBuilder()
        {

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                _ = Executer.RunInCommandFile("ufw allow " + AppSetting.iToolConfigure.ServerPort);
                _ = Executer.RunInCommandFile("ufw allow " + AppSetting.iToolConfigure.ServerGatewayPort);
            }

            var builder = new iToolHostBuilder();

            var clusterOptions = new AdoNetClusterOptions();

            // 数据库配置
            clusterOptions.AdoNetOptions = AppSetting.iToolConfigure.iToolBaseDatabaseList?.Any() == true ?
                AppSetting.iToolConfigure.iToolBaseDatabaseList.First() :
                new AdoNetOptions
                {
                    DataSource = "127.0.0.1,2433",
                    UID = "sa",
                    PWD = "zhuJIAN320"
                };

            // 服务配置
            clusterOptions.EndpointsOptions = new EndpointsOptions
            {
                AdvertisedIP = string.IsNullOrWhiteSpace(AppSetting.iToolConfigure.Ip) ? null : IPAddress.Parse(AppSetting.iToolConfigure.Ip),
                Port = AppSetting.iToolConfigure.ServerPort,
                GatewayPort = AppSetting.iToolConfigure.ServerGatewayPort
            };

            // 集群配置
            clusterOptions.ClusterOptions = new ClusterIdentificationOptions
            {
                ClusterId = "iToolServiceCluster",
                ServiceId = "iToolService"
            };

            // 响应超时时间配置
            clusterOptions.ResponseTimeout = TimeSpan.FromSeconds(10);

            builder.ConfigureServices(this.INIIServices);

            builder.UseAdoNetClustering(clusterOptions);

            return builder;
        }

        /// <summary>
        /// 初始化所有IServices
        /// </summary>
        private void INIIServices(IServiceCollection services)
        {
            var types = AppDomain.CurrentDomain.GetAssemblies()
                            .SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IDIRegister))))
                            .ToArray();

            foreach (var aHandler in types)
            {
                var iRegister = (IDIRegister)Activator.CreateInstance(aHandler);

                iRegister.Execute(services);
            }
        }
    }
}
